import { EditBox } from 'cc';
import { Global } from '../../../script/Global';
import { _decorator, Component } from 'cc';
import { GameSocket } from '../../..//script/socket/GameSocket';
import { show_hint } from '../../../sgame/ui/SUI';
import { SceneManager } from '../../../script/scene/SceneManager';
import { lerror, llog } from '../../..//sgame/logger/Logger';
import { Player } from '../../player/script/Player';
import { ISC_LOGIN } from '../../../proto/proto';
import { PlayerProto } from '../../player/script/PlayerProto';
const { ccclass, property } = _decorator;

@ccclass('LoginScene')
export class LoginScene extends Component {
    start() {
        let playerEb = this.node.Component("playerId/edbox", EditBox);
        let urlEb = this.node.Component("url/edbox", EditBox);

        this.node.OnClickChild("login", () => {
            let playerId = playerEb.string;
            let url = `ws://${urlEb.string}`;
            if (playerId.length == 0) {
                show_hint("player id is empty!");
                return;
            }

            // 效验url
            if (/ws:\/\/[^:]+:[0-9]+/.test(url) == false) {
                show_hint("can't parse url: " + url);
                return;
            }

            let gameSocket = new GameSocket(url);
            gameSocket.enableHeartBeat(PlayerProto.HEART_BEAT);
            gameSocket.connect(() => {
                gameSocket.request(PlayerProto.LOGIN, {
                    token: playerId
                }, (data: ISC_LOGIN) => {
                    if (data.code != 1) {
                        lerror(`login failed, code: ${data.code}, msg: ${data.msg}`);
                        gameSocket.close();
                        return;
                    }

                    Global.gameSocket = gameSocket;
                    Global.token = playerId;
                    show_hint("login success");
                    Global.me = new Player(data.player);

                    SceneManager.instance().enter("hall");
                });
            }, (event: Event) => {
                lerror("connect failed!");
                show_hint("connect failed! " + event.toString());
            });
        });
    }
}
